import axios from 'axios';
import {UserService} from "@/middleware/db/userService";
import Vue from 'vue'
import {dbHelper} from "@/middleware/db/dbService";
import router from '@/router'
import {_} from 'lodash';

axios.defaults.timeout = 1200000;


if (process.env.NODE_ENV === 'dev') {
    axios.defaults.baseURL = 'http://192.168.0.68:8080/api';
} else if (process.env.NODE_ENV === 'test') {
    axios.defaults.baseURL = 'http://192.168.0.68:8080/api';
} else if (process.env.NODE_ENV === 'uat') {
    axios.defaults.baseURL = 'http://192.168.0.68:8080/api';
} else if (process.env.NODE_ENV === 'release') {
    axios.defaults.baseURL = 'http://192.168.0.68:8080/api';
} else {
    axios.defaults.baseURL = 'http://192.168.0.68:8080/api';
}

axios.interceptors.request.use(async (config) => {
    const currentUser = await UserService.getCurrentUser();
    if (_.isUndefined(currentUser)) {
        console.log('peter === token' + currentUser.token);
        config.headers['Authorization'] = currentUser.token;
    } else {
        config.headers['Authorization'] = '';
    }
    console.log('peter request url ' + config.url);
    return config;
}, (error) => {
    return Promise.reject(error)
});


axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    // if (error.response.status === 401) {
    dbHelper.clearAllData();
    router.push("/login");
    // }
    return Promise.reject(error);
});

export function fetch(url, params = {}) {
    return new Promise((resolve) => {
        axios.get(url, {
            params: (params.done === undefined && params.error === undefined) ? params : params.options
        })
            .then(response => {
                if (response.data.code === 200) {
                    resolve(response.data);
                } else {
                    handlerErrorTip(response, params);
                }
            })
            .catch(() => {
                Vue.prototype.$message.error('网络异常，请稍后重试');
            });
    })
}

function handlerErrorTip(response, params) {
    if (_.isBoolean(params.showTip)) {
        Vue.prototype.$message.error(response.data.message);
    }
}

export function post(url, params = {}) {
    return new Promise((resolve) => {
        axios.post(url,
            (params.done === undefined && params.error === undefined) ? params : params.options)
            .then(response => {
                if (response.data.code === 200) {
                    resolve(response.data);
                    return;
                }
                handlerErrorTip(response, params);
            })
            .catch(() => {
                Vue.prototype.$message.error('网络异常，请稍后重试');
            });
    });
}

